//
//  TextViewViewController.m
//  TextView
//

#import "TextViewViewController.h"

UIScrollView *myScrollView;
UITextView *myTextView;

@implementation TextViewViewController

- (void)buttonClick:(id)sneder {
	[myTextView resignFirstResponder];
}

- (void)viewDidLoad {
    [super viewDidLoad];
	
	CGRect viewRect = [self.view bounds];
	myScrollView = [[UIScrollView alloc] initWithFrame:viewRect];
	myScrollView.contentSize = viewRect.size;
	[self.view addSubview:myScrollView];

	CGRect buttonFrame = CGRectMake(10, 10, 60, 32);
	UIButton *keyboardToggle = [UIButton buttonWithType:UIButtonTypeRoundedRect];
	[keyboardToggle setTitle:@"hide" forState:UIControlStateNormal];
	[keyboardToggle addTarget:self action:@selector(buttonClick:) forControlEvents:UIControlEventTouchUpInside];
	keyboardToggle.frame = buttonFrame;
	[myScrollView addSubview:keyboardToggle];
	
	CGRect textRect = CGRectMake(10, 60, 300, 200);
	myTextView = [[UITextView alloc] initWithFrame:textRect];
	
	myTextView.font = [UIFont systemFontOfSize:22.0];
	myTextView.keyboardType = UIKeyboardTypeDefault;
	myTextView.returnKeyType = UIReturnKeyGo;
	myTextView.delegate = self;
	[myScrollView addSubview:myTextView];
	
	[myTextView release];
	[myScrollView release];
}

- (void)textViewDidBeginEditing:(UITextView *)textView {
	
	float keyboardHeight;
	if ([UIDevice currentDevice].orientation
		== UIDeviceOrientationPortrait | UIDeviceOrientationPortraitUpsideDown) {
		keyboardHeight = 216.0;
	} else {
		keyboardHeight = 162.0;
	}

	CGRect textViewRect = textView.frame;
	float textViewBottom = textViewRect.origin.y + textViewRect.size.height;
	CGRect viewRect = [myScrollView bounds];
	float keyboardTop = viewRect.size.height - keyboardHeight;
	float scrollOffset = fabs(textViewBottom - keyboardTop);
	[myScrollView setContentOffset:CGPointMake(0, scrollOffset) animated:YES];
}

- (void)textViewDidEndEditing:(UITextView *)textView {
	[myScrollView setContentOffset:CGPointMake(0, 0) animated:YES];
}

- (void)dealloc {
    [super dealloc];
}

@end
